﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

#if !SILVERLIGHT
namespace UIT.WPF.Renderers
#else
namespace UIT.Silverlight.Renderers
#endif
{
	public class DataGridRenderer :
#if !SILVERLIGHT
		WpfRenderer<Controls.Data.DataGrid, Grid>
#else
		SlRenderer<Controls.Data.DataGrid, Grid>
#endif
	{
		public override void Render(Controls.Data.DataGrid control)
		{

			if (control.DataSource != null)
			{
				Result = new Grid();
				foreach (UIT.Controls.Data.Column column in control.DataGridColumns)
					Result.ColumnDefinitions.Add(new ColumnDefinition());

				bool isEven = false;

				foreach (object row in control.DataSource.Select(new Controls.Data.SelectArgument()))
				{
					Result.RowDefinitions.Add(new RowDefinition());

					int c = 0;
					foreach (UIT.Controls.Data.Column column in control.DataGridColumns)
					{

						UIElement child;
						if (isEven || column.AlternatingItemTemplate == null)
							child = Manager.Render(column.ItemTemplate.CreateInstance(row));
						else
							child = Manager.Render(column.AlternatingItemTemplate.CreateInstance(row));
#if !SILVERLIGHT
						Grid.SetColumn(child, c);
						Grid.SetRow(child, Result.RowDefinitions.Count - 1);
#else
						Grid.SetColumn((FrameworkElement)child, c);
						Grid.SetRow((FrameworkElement)child, Result.RowDefinitions.Count - 1);
#endif
						Result.Children.Add(child);
						c++;
					}
					isEven = !isEven;
				}
			}
		}
	}
}
